import 'package:flutter/material.dart';
import 'package:grasp_flutter_app/utils/dao/bill_types_dao.dart';
import 'package:grasp_flutter_app/utils/model/bill_xsck.dart';
import 'package:grasp_flutter_app/utils/view/ListItem.dart';
import 'package:grasp_flutter_app/utils/view/PopupMenuWidget.dart';
import 'package:grasp_flutter_app/utils/view/RightSheet.dart';
import 'package:grasp_flutter_app/utils/view/TriangleClipper.dart';
import 'package:grasp_flutter_app/utils/view/mixin/PageQueryListState.dart';
import '../utils/utils.dart';
import '../utils/dao/bill_xsck_dao.dart';
import '../utils/view/TabsEx.dart' as tabs;

/// 单据页
class BillPage extends StatefulWidget {
  BillPage({Key key, this.onModeChange}) : super(key: key);

  List<BillXSCKItem> data;
  ListViewState listState = ListViewState(controller: ScrollController());
  List<BillTypeList> billTypes;
  ValueChanged<bool> onModeChange;

  @override
  State<StatefulWidget> createState() {
    return _BillPageState();
  }
}


class _BillPageState extends PageQueryListState<BillPage> with PageDataMixin<BillXSCKItem>, SingleTickerProviderStateMixin {
  bool _allowLoadMore = false;
  bool _isSearch = false;
  bool _isSelect = false;
  int _selectCount = 0;
  int _sortType = 0;

  TextEditingController _editingController = new TextEditingController();
  TabController _tabController;

  /// 下拉控件最大高度
  final _DropdownMenuMaxHeight = SizeUtils.height * 0.75;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    print("initState");
    super.initState();
    //useSliver = false;
    _tabController = new TabController(length: 5, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  List<BillXSCKItem> getData() {
    return widget.data;
  }

  @override
  ListViewState getListState() {
    return widget.listState;
  }

  @override
  Widget getTitle() {
    if (_isSearch) {
      return Container(
        width: double.infinity,
        margin: const EdgeInsets.only(top: 12.0, bottom: 12.0),
        padding: const EdgeInsets.only(left: 0.0, right: 16.0),
        child: buildSearchEdit(),
        decoration: BoxDecoration(
          color: Styles.mainBackgroundColor,
          shape: BoxShape.rectangle,
          borderRadius: BorderRadius.circular(5.0),
        ),
      );
    }
    String title = "全部单据";
    if (widget.billTypes != null) {
      int selected = 0;
      for (int i=0; i<widget.billTypes.length; i++) {
        if (widget.billTypes[i].items == null) continue;
        for (int j=0; j < widget.billTypes[i].items.length; j++) {
          if (widget.billTypes[i].items[j].checked) {
            title = widget.billTypes[i].items[j].name + "...";
            selected++;
            break;
          }
        }
        if (selected > 0) break;
      }
    }

    return GestureDetector(
      child: Padding(
        child: IconText(text: title, icon: Icon(Icons.arrow_drop_down, color: Styles.primaryContrastValue), useWrap: true, overflow: TextOverflow.ellipsis, iconLast: true),
        padding: const EdgeInsets.only(left: 8.0),
      ),
      onTap: () {
        if (widget.billTypes == null) {
          widget.billTypes = BillTypesDao.getBillTypes();
        }
        showDownView();
        //_controller.show(0);
      },
    );
  }

  @override
  String getSubTitle() {
    if (!_isSelect) return null;
    return _selectCount == 0 ? "选择单据" : "已选择$_selectCount张单据";
  }

  @override
  List<Widget> buildHeaderActions() {
    if (_isSearch || _isSelect) return [
      Container(
        width: 50.0,
        child: FlatButton(
          padding: EdgeInsets.zero,
          child: Text("取消", style: TextStyle(color: Styles.primaryContrastValue)),
          onPressed: () {
            if (_isSelect) {
              _isSelect = false;
              _changeSelectState(false);
              if (widget.onModeChange != null)
                widget.onModeChange(_isSelect);
            }
            setState(() {
              _isSearch = false;
            });
          },
        ),
      )
    ];
    return [
      IconButton(icon: Icon(Icons.search, color: Styles.primaryContrastValue), onPressed: () {
        setState(() {
          _isSearch = !_isSearch;
        });
      })
    ];
  }

  @override
  Widget buildLeading() {
    if (_isSearch) return null;
    return Container(
      width: 50.0,
      child: FlatButton(
        padding: EdgeInsets.zero,
        child: Text(_isSelect ? "全选" : "批量", style: TextStyle(color: Styles.primaryContrastValue)),
        onPressed: () {
          setState(() {
            if (!_isSelect) {
              _isSelect = !_isSelect;
              if (widget.onModeChange != null)
                widget.onModeChange(_isSelect);
            } else {
              _changeSelectState(true);
            }
          });
        },
      ),
    );
  }

  @override
  buildAppBarBottom(BuildContext context) {
    Widget _buildSortText() {
      switch (_sortType) {
        case 1:
          return Text("修改时间", style: TextStyle(color: Styles.colorLight(Styles.primaryValue, 0.2)));
        case 2:
          return Text("创建日期", style: TextStyle(color: Styles.colorLight(Styles.primaryValue, 0.2)));
        default:
          return Text("排序");
      }
    }

    return tabs.TabBar(
      controller: _tabController,
      labelStyle: TextStyle(fontSize: Styles.textSmallSize),
      tabs: <Widget>[
        buildTabBarItem(Text("全部")),
        buildTabBarItem(Text("待审核")),
        buildTabBarItem(Text("已审核")),
        buildTabBarItem(_buildSortText(), icon: Icon(Icons.unfold_more, size: 14.0), isPopup: true, onPopup: (state) {
          var context = state.context;
          final RenderBox button = context.findRenderObject();
          final RenderBox overlay = Overlay.of(context).context.findRenderObject();
          final RelativeRect position = new RelativeRect.fromRect(
            new Rect.fromPoints(
              button.localToGlobal(Offset(0.0, 45.0 + MediaQuery.of(context).padding.top - 8.0), ancestor: overlay),
              button.localToGlobal(button.size.bottomRight(Offset.zero), ancestor: overlay),
            ),
            Offset.zero & overlay.size,
          );
          showModalDrapDownSheet(context: context, offset: position.top, paddingOffset: 8.0, elevation: 0.0, builder: (context) {
            return Column(
              children: <Widget>[
                SizedBox(height: 2.0),
                buildPopupTriangle(position.left + (position.right - position.left) / 2),
                Container(
                  color: Styles.white,
                  child: DefaultTextStyle(
                    style: TextStyle(fontSize: Styles.textSmallSize),
                    child: Column(
                      children: <Widget>[
                        buildSortPopupMenuItem(title: "业务日期 (从近到远)", value: 0, icon: Icons.help, trailing: Container(
                          child: Text("默认排序", style: Styles.smallPrimaryContrastText),
                          padding: const EdgeInsets.fromLTRB(5.0, 2.0, 5.0, 2.0),
                          decoration: BoxDecoration(color: Styles.primaryValue, borderRadius: BorderRadius.circular(3.0)),
                        )),
                        buildSortPopupMenuItem(title: "修改时间 (从近到远)", value: 1, icon: Icons.help),
                        buildSortPopupMenuItem(title: "创建日期 (从近到远)", value: 2),
                      ],
                    ),
                  ),
                )
              ],
            );
          });
        }),
        buildTabBarItem(Text("筛选"), icon: Icon(Icons.filter_list, size: 14.0), onTap: () {
          showModalRightSheet(context: context, clickEmptyPop: false, builder: (context) {
            return FilterRightPopupView();
          });
        })
      ],
      labelPadding: EdgeInsets.zero,
      //indicatorPadding: const EdgeInsets.only(bottom: 2.0, left: 8.0, right: 8.0),
    );
  }

  Widget buildSortPopupMenuItem({String title, int value,  IconData icon, Widget trailing}) {
    return ListItem(selected: _sortType == value, title: Row(children: <Widget>[
      Text(title),
      SizedBox(width: 12.0),
      icon == null ? SizedBox(width: 8.0) : GestureDetector(
        child: Icon(icon, color: Styles.subTextColor),
        onTap: () {
          showDialog(context: context, builder: (context) {
            return AlertDialog(
              title: Text(title),
              content: Text("发生实际业务的日期 ,比如在2月1号发生销售业务(选择2月1号作为业务日期),销售报表的数据就会统计到那天"),
              actions: <Widget>[
                FlatButton(child: Text("知道了"), onPressed: () {
                  Navigator.pop(context);
                })
              ],
            );
          });
        },
      ),
      Expanded(child: Container(
        alignment: Alignment.centerRight,
        child: trailing != null ? trailing : _sortType == value ? Icon(Icons.check, color: Styles.primaryValue) : null,
      ))
    ]), onTap: () {
      Navigator.pop(context);
      setState(() {
        _sortType = value;
      });
    });
  }

  Widget buildTabBarItem(Widget title, {Icon icon, bool isPopup, VoidCallback onTap, ValueChanged<State> onPopup}) {
    return tabs.Tab(
      child: title,
      icon: icon,
      iconPosition: tabs.IconPosition.right,
      onTap: onTap,
      onPopup: onPopup,
      disActive: onTap != null || onPopup != null,
    );
  }

  bool getAllowLoadMore() {
    return _allowLoadMore;
  }

  @override
  Widget buildBodyView() {
    if (_isSelect) {
      return Column(
        children: <Widget>[
          Expanded(
            child: super.buildBodyView(),
          ),
          buildBottomTools(context),
        ],
      );
    }
    return super.buildBodyView();
  }

  @override
  Widget buildBody() {
    return super.buildBody();
  }

  @override
  Widget buildListItemView(BuildContext context, BillXSCKItem item, int index) {
    List<Widget> _body = [
      Row(
        children: <Widget>[
          SizedBox(width: 16.0),
          _isSelect ? Icon(item.select ? Icons.check_circle : Icons.radio_button_unchecked, color: item.select ? Styles.primaryValue : Styles.subLightTextColor, size: 16.0) : SizedBox(),
          SizedBox(width: _isSelect ? 8.0 : 0.0),
          Expanded(child: Text("销售出库单: ${item.id}", style: Styles.minSubLightText)),
          Text("${item.state}", style: Styles.smallPrimaryText),
          SizedBox(width: 16.0),
        ],
      ),
      SizedBox(height: 8.0),
      Divider(height: 1.0),
      Padding(
        padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 8.0, bottom: 8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(child: Text("${item.supplier ?? "暂无供应商"}", style: Styles.middleText)),
                Text("¥ ${item.money.toStringAsFixed(2)}", style: Styles.smallText),
              ],
            ),
            SizedBox(height: 4.0),
            Text("出库仓库: ${item.store}", style: Styles.minSubText),
            SizedBox(height: 4.0),
            Text("商品概要: ${item.remark ?? "无"}", style: Styles.minSubText),
          ],
        ),
      )
    ];

    if (!_isSelect) {
      _body.addAll([
        Divider(height: 1.0),
        Container(
          width: double.infinity,
          height: 38.0,
          padding: const EdgeInsets.only(right: 16.0, left: 16.0, top: 8.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              GButton(
                child: Row(
                  children: <Widget>[
                    Icon(Icons.print, color: Styles.mainTextColor.withAlpha(75), size: Styles.textSmallSize + 2.0),
                    SizedBox(width: 4.0),
                    Text(Utils.getLocale(context).print, style: Styles.smallSubText)
                  ],
                ),
                border: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(3.0),
                    side: BorderSide(color: Styles.primaryValue, width: 0.5)
                ),
                onPressed: () {
                  Utils.toast(Utils.getLocale(context).print);
                },
              ),
              SizedBox(width: 12.0),
              GButton(
                child: Row(
                  children: <Widget>[
                    Icon(Icons.account_balance_wallet, color: Styles.primaryContrastValue, size: Styles.textSmallSize + 2.0),
                    SizedBox(width: 4.0),
                    Text("审核", style: Styles.smallPrimaryContrastText)
                  ],
                ),
                color: Styles.primaryValue,
                onPressed: () {
                  Utils.toast("审核");
                },
              ),
            ],
          ),
        )
      ]);
    }

    Widget view = Container(
      width: double.infinity,
      margin: const EdgeInsets.only(top: 4.0, bottom: 8.0, left: 16.0, right: 16.0),
      child: Material(
        elevation: 0.0,
        child: InkWell(
          borderRadius: BorderRadius.circular(6.0),
          child: Container(
            decoration: BoxDecoration(
                color: Colors.white54,
                borderRadius: BorderRadius.circular(6.0),
            ),
            padding: const EdgeInsets.fromLTRB(0.0, 16.0, 0.0, 6.0),
            child: Column(
              children: _body,
            ),
          ),
          onTap: () {
            doItemClick(item);
          },
        ),
      ),
    );

    // 检测日期 , 如果是第一行或与上一行不一样, 则在此行上加入日期显示
    BillXSCKItem up;
    if (index > 0) up = data[index - 1];
    if (up == null || up.date.year != item.date.year || up.date.month != item.date.month || up.date.day != item.date.day) {
      view = Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 16.0),
          Padding(
            padding: const EdgeInsets.only(left: 24.0),
            child: Text(Utils.dateToStr(item.date), style: Styles.minSubText),
          ),
          SizedBox(height: 4.0),
          view,
        ],
      );
    }

    return view;
  }

  Widget buildSearchEdit() {
    return TextField(
      style: Styles.smallText,
      controller: _editingController,
      textAlignVertical: TextAlignVertical.center,
      decoration: new InputDecoration(
          border: InputBorder.none,
          hintText: "请输入单据编号进行搜索",
          hintStyle: Styles.smallSubText,
          contentPadding: EdgeInsets.only(left: 0.0, right: 0.0, top: 0.0, bottom: 0.0),
          suffixIcon: _editingController.text == null || _editingController.text.isEmpty
              ? null
              : IconButton(
              padding: EdgeInsets.only(left: 8.0, right: 8.0, top: 0.0, bottom: 0.0),
              icon: Icon(
                Icons.close,
                color: Styles.subTextColor,
              ),
              highlightColor: Styles.nullColor,
              onPressed: () {
                _editingController.clear();
                doFilter(null);
              }),
          prefixIcon: new Container(
            //padding: EdgeInsets.only(left: 16.0, right: 8.0, top: 0.0, bottom: 0.0),
              child: new Icon(
                Icons.search,
                color: Styles.subTextColor,
              )
          )
      ),
      onChanged: (text) {
        doFilter(_editingController.text);
      },
    );
  }

  /// 生成底部编辑工具栏
  Widget buildBottomTools(BuildContext context) {
    return Material(
      elevation: 8.0,
      child: Container(height: 50.0, color: Styles.primaryValue, padding: EdgeInsets.only(top: 4.0, bottom: 4.0), child: Row(
        children: <Widget>[
          buildBottomToolsItem("删除", Icons.delete_outline, () {}),
          buildBottomToolsItem("复制", Icons.content_copy, () {}),
          buildBottomToolsItem("审核", Icons.list, () {}),
          buildBottomToolsItem("红冲", Icons.redeem, () {}),
          buildBottomToolsItem("打印", Icons.local_printshop, () {}),
        ],
      )),
    );
  }

  Widget buildBottomToolsItem(String title, IconData icon, VoidCallback onTap) {
    return Expanded(
      child: Material(
        color: Styles.primaryValue,
        child: InkWell(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Icon(icon, color: Styles.primaryContrastValue, size: 16.0),
              Text(title, textAlign: TextAlign.center, style: TextStyle(color: Styles.primaryContrastValue, fontSize: Styles.textMinSize)),
            ],
          ),
          onTap: onTap,
        ),
      ),
    );
  }

  @override
  Future<bool> doRefresh(bool isReLoad, {bool setWait = true}) async {
    if (!await super.doRefresh(isReLoad, setWait: setWait))
      return false;

    if (isReLoad) {
      BillXSCKDao.clear();
      _allowLoadMore = false;
      widget.listState.currentPage = 1;
    }

    await BillXSCKDao.getList(widget.listState.currentPage - 1, (newData) {
      if (Consts.debug) print("newData.length: ${newData?.length}");
      if (isReLoad && data != null)
        data.clear();
      if (newData != null) {
        if (data == null)
          widget.data = [];
        data.addAll(newData);
        widget.data = data;
      }
      _allowLoadMore = !(newData == null || newData.length < Consts.PAGE_SIZE);
      setState(() {
        widget.listState.isLoadMore = false;
        widget.listState.isWait = false;
      });
    });

    return true;
  }

  void doItemClick(BillXSCKItem item) {
    if (_isSelect) {
      setState(() {
        if (item.select)
          _selectCount--;
        else
          _selectCount++;
        item.select = !item.select;
      });
      return;
    }
    Utils.toast("item click");
  }

  void doFilter(String text) {

  }

  void _changeSelectState(bool v) {
    _selectCount = 0;
    this.data.forEach((item) {
      item.select = v;
      if (v) _selectCount++;
    });
  }

  void showDownView() {
    showModalDrapDownSheet(context: context, offset: 50.0 + MediaQuery.of(context).padding.top - 8.0, paddingOffset: 8.0, elevation: 0.0, builder: (context) {
      Map<BillTypeItem, bool> _checked = {};
      if (widget.billTypes != null) {
        widget.billTypes.forEach((v) {
          if (v.items == null) return;
          v.items.forEach((item) {
            _checked[item] = item.checked;
          });
        });
      }
      return DownDropListView(
        // key: Key(Utils.currentTimeMillis().toString()), // 必须每次重建
        billTypes: widget.billTypes,
        checkeds: _checked,
        maxHeight: _DropdownMenuMaxHeight,
        onSelected: () {
          setState(() {});
        },
      );
    });
  }
}

Widget buildPopupTriangle([double offsetX = 0.0]) {
  return Container(
    width: 8.0,
    height: 6.0,
    margin: EdgeInsets.only(left: offsetX),
    child: ClipPath(
      clipper: TriangleClipper(),
      child: Container(color: Styles.white),
    ),
  );
}

/// 下拉菜单组件
class DownDropListView extends StatefulWidget {
  final List<BillTypeList> billTypes;
  final Map<BillTypeItem, bool> checkeds;
  final double maxHeight;
  final VoidCallback onSelected;

  const DownDropListView({Key key, this.billTypes, this.maxHeight, this.checkeds, this.onSelected}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return _DownDropListState();
  }
}

const vhs = 8.0;
Widget buildCheckButton({String text, Widget child, bool checked = false, bool expanded = false, VoidCallback onTap}) {
  Widget v = Container(
    height: 35.0,
    alignment: Alignment.center,
    padding: const EdgeInsets.fromLTRB(16.0, 4.0, 16, 4.0),
    child: child ?? Text(text, style:checked ? Styles.smallPrimaryText : Styles.smallText),
    decoration: BoxDecoration(
        color: Styles.mainBackgroundColor,
        borderRadius: BorderRadius.circular(3.0)
    ),
  );
  if (onTap != null) {
    v = InkWell(
      child: v,
      onTap: onTap,
    );
  }
  v = Padding(
    padding: const EdgeInsets.only(right: vhs, bottom: vhs),
    child: v,
  );
  if (expanded) {
    v = Expanded(child: v);
  }
  return v;
}

int _downDropRef = 0;

class _DownDropListState extends State<DownDropListView> {
  static const double rs = 6.0;

  double _listHeight = 0.0;
  bool isChange = false;

  List<Widget> buildListView() {
    List<Widget> views = [];
    _listHeight = vhs * 2;
    isChange = false;

    if (widget.billTypes != null) {
      widget.billTypes.forEach((v) {
        _listHeight = _listHeight + rs + 25.0;
        views.add(Text(v.name, style: Styles.minText));
        if (v.items == null || v.items.isEmpty)
          return;
        List<Widget> items = Common.buildGridView<BillTypeItem>(v.items,
            builder: (item) {
              if (!isChange && widget.checkeds[item] != item.checked) isChange = true;
              return Expanded(
                child: GestureDetector(
                  child: buildCheckButton(text: item.name, checked: widget.checkeds[item]),
                  onTap: () {
                    setState(() {
                      widget.checkeds[item] = !widget.checkeds[item];
                    });
                  },
                ),
              );
            },
            builderRow: (row, items) {
              _listHeight = _listHeight + 35.0 + vhs;
              return null;
            }
        );
        views.add(Container(
          padding: const EdgeInsets.only(top: rs, bottom: rs),
          child: Column(
            children: items,
          ),
        ));
      });
    }

    if (_listHeight < 50.0) _listHeight = 50.0;
    if (widget.maxHeight != null && _listHeight > widget.maxHeight - 55.0)
      _listHeight = widget.maxHeight - 55.0;

    return views;
  }

  @override
  Widget build(BuildContext context) {
    _downDropRef++;
    if (Consts.debug) print("_downDropRef: $_downDropRef");

    return Container(
      width: double.infinity,
      child: Column(
        children: <Widget>[
          const SizedBox(height: 2.0),
          buildPopupTriangle(),
          Container(
            color: Styles.white,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: double.infinity,
                  height: _listHeight,
                  padding: const EdgeInsets.only(left: 0.0, right: 0.0, top: 16.0, bottom: 0.0),
                  child: ListView(
                    padding: const EdgeInsets.only(left: 16.0, right: 8.0),
                    children: buildListView(),
                  ),
                ),
                const Divider(height: 1.0),
                Container(
                  height: 50.0,
                  padding: const EdgeInsets.fromLTRB(8.0, 4.0, 8.0, 4.0),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: GButton(child: Text("清除"), onPressed: () {
                          doClearSelected();
                        }),
                      ),
                      const SizedBox(width: 8.0),
                      Expanded(
                        child: GButton(child: Text("确定"), color: Styles.primaryValue, textColor: Styles.primaryContrastValue, onPressed: !isChange ? null :  () {
                          doApplySelected();
                          if (widget.onSelected != null)
                            widget.onSelected();
                          Navigator.pop(context);
                        }),
                      )
                    ],
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  void doClearSelected() {
    if (widget.billTypes == null) return;
    widget.billTypes.forEach((v) {
      if (v.items == null) return;
      v.items.forEach((item) {
        widget.checkeds[item] = false;
      });
    });
    setState(() {});
  }

  void doApplySelected() {
    widget.checkeds.forEach((item, value) {
      item.checked = value;
    });
  }
}

class FilterRightPopupView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _FilterRightPopupViewState();
  }
}

class _FilterRightPopupViewState extends State<FilterRightPopupView> {
  List<bool> _stats = [false, false, false];
  int _ftype = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: (MediaQuery.of(context).size.width - SizeUtils.getAxisX(120.0)),
      child: Column(
        children: <Widget>[
          Expanded(
            child: buildListView(),
          ),
          Container(
            child: Row(
              children: <Widget>[
                Expanded(child: GButton(child: Text("重置"), color: Styles.miWhite, styles: Styles.smallText, border: Border(), onPressed: () {

                })),
                Expanded(child: GButton(child: Text("确定"), color: Styles.primaryValue, styles: Styles.smallPrimaryContrastText, border: Border(), onPressed: () {
                  Navigator.pop(context);
                })),
              ],
            ),
          )
        ],
      ),
    );
  }

  final List<String> fItems = ["业务日期", "创建时间", "最后修改时间"];

  Widget buildListView() {
    return ListView(
      padding: EdgeInsets.zero,
      children: <Widget>[
        Padding(
          padding: EdgeInsets.only(left: 12.0, right: 8.0, bottom: 8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text("订单状态", style: Styles.minText),
              SizedBox(height: 16.0),
              Row(
                children: <Widget>[
                  buildCheckButton(text: "待审核", expanded: true, checked: _stats[0], onTap: () {
                    setState(() { _stats[0] = !_stats[0]; });
                  }),
                  buildCheckButton(text: "已审核", expanded: true, checked: _stats[1], onTap: () {
                    setState(() { _stats[1] = !_stats[1]; });
                  }),
                  buildCheckButton(text: "已红冲", expanded: true, checked: _stats[2], onTap: () {
                    setState(() { _stats[2] = !_stats[2]; });
                  }),
                ],
              ),
              SizedBox(height: 12.0),
              Divider(height: Styles.lineSize),
              SizedBox(height: 16.0),
              Text("单据来源", style: Styles.minText),
              SizedBox(height: 16.0),
              Row(
                children: <Widget>[
                  buildCheckButton(text: "手工开单", expanded: true),
                  buildCheckButton(text: "微商城下单", expanded: true),
                ],
              ),
              SizedBox(height: 12.0),
              Divider(height: Styles.lineSize),
              SizedBox(height: 16.0),
              PopupMenuWidget(child: Row(mainAxisSize: MainAxisSize.min, children: <Widget>[Text(fItems[_ftype], style: Styles.minText), SizedBox(width: 2.0), Icon((Icons.arrow_drop_down))]), onPopup: (state) {
                Common.showButtonMenu<String>(state.context, state, items: buildRightPopupItems<String>(fItems), onSelected: (v) {
                  setState(() {
                    _ftype = fItems.indexOf(v);
                  });
                });
              }),
              SizedBox(height: 8.0),
              GestureDetector(
                  child: Container(
                    height: 36.0,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(3.0),
                        border: Border.all(color: Styles.lineColor, width: 0.5)
                    ),
                    padding: EdgeInsets.all(8.0),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: Text("开始日期 - 结束日期", style: Styles.minSubLightText),
                        ),
                        Icon(Icons.date_range, color: Styles.lineColor, size: 18.0)
                      ],
                    ),
                  ),
                  onTap: () {

                  }
              ),
              SizedBox(height: 12.0),
              Divider(height: Styles.lineSize),
              SizedBox(height: 16.0),
              ListItem(title: Text("供应商"), trailing: Icon(Icons.keyboard_arrow_right, size: 16.0), subtitle: Text("请选择"), dense: true, isRow: true, onTap: (){}),
              ListItem(title: Text("客户"), trailing: Icon(Icons.keyboard_arrow_right, size: 16.0), subtitle: Text("请选择"), dense: true, isRow: true, onTap: (){}),
              ListItem(title: Text("仓库"), trailing: Icon(Icons.keyboard_arrow_right, size: 16.0), subtitle: Text("请选择"), dense: true, isRow: true, onTap: (){}),
              ListItem(title: Text("制单员"), trailing: Icon(Icons.keyboard_arrow_right, size: 16.0), subtitle: Text("请选择"), dense: true, isRow: true, onTap: (){}),
              ListItem(title: Row(children: <Widget>[Text("销售员"), SizedBox(width: 8.0), Icon(Icons.help, size: 16.0, color: Styles.subTextColor)],), trailing: Icon(Icons.keyboard_arrow_right, size: 16.0), subtitle: Text("请选择"), dense: true, isRow: true, onTap: (){}),
            ],
          ),
        ),
      ],
    );
  }

  List<PopupMenuEntry<T>> buildRightPopupItems<T>(List<T> items) {
    List<PopupMenuItem<T>> list = [];
    items.forEach((v) {
      list.add(PopupMenuItem<T>(
        value: v,
        child: Text("$v"),
      ));
    });
    return list;
  }
}